//
//  HexConverter.m
//  zhangjiantest2
//
//  Created by Mac on 2024/7/5.
//

#import <Foundation/Foundation.h>
#import "HexConverter.h"

@implementation HexConverter

+ (NSData *)dataFromHexString:(NSString *)hexString {
    NSMutableData *data = [[NSMutableData alloc] init];
    unsigned char wholeByte;
    char byteChars[3] = {'\0', '\0', '\0'};
    int i = 0;
    int length = (int)hexString.length;
    while (i < length) {
        byteChars[0] = [hexString characterAtIndex:i++];
        byteChars[1] = [hexString characterAtIndex:i++];
        wholeByte = strtol(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }
    return data;
}


+ (NSString *)hexStringFromData:(NSData *)data {
    const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
    if (!dataBuffer) {
        return [NSString string];
    }

    NSUInteger dataLength = [data length];
    NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];

    for (int i = 0; i < dataLength; ++i) {
        [hexString appendFormat:@"%02x", dataBuffer[i]];
    }

    return hexString;
}
@end
